<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { useGroupList,useCompanyStore } from '../../store';
import { payListType } from '../../types';
import { ElAlert, ElMessage, ElNotification } from 'element-plus';
import { useRouter } from 'vue-router';
const useCompany = useCompanyStore()

const search = ref('')

// 使用 reactive 创建响应式数据
const tableData = reactive<{
  items: payListType[];
  selected: payListType[];
}>({
  items: [],
  selected: []
})
// 获取公司列表
const companyList = computed(() => useCompany.company)

// 获取年月日
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1);
const day = date.getDate();

// 初始化表格数据
const initializeTableData = () => {
  tableData.items = companyList.value.map(company => ({
    id: company.id,
    year: year,
    month: month,
    day: day,
    name: company.name,
    account: company.account,
    address: company.address,
    amount: null,
    remark: ''
  }))
}

// 添加搜索过滤
const filteredList = computed(() => {
  if (!search.value) return companyList.value
  return companyList.value.filter(company => 
    company.name?.includes(search.value) ||
    company.account?.includes(search.value) ||
    company.address?.includes(search.value)
  )
})

// 金额输入处理
const handleAmountInput = (value: string, row: payListType) => {
  // console.log('row:', row)
  // 只允许输入数字和小数点
  const numericValue = value.replace(/[^\d.]/g, '')
  // 确保只有一个小数点
  const dotCount = numericValue.split('.').length - 1
  if (dotCount > 1) {
    return
  }
  row.amount = numericValue === '' ? null : numericValue
  tableData.items.filter(item => item.id === row.id)[0].amount = row.amount
}

// 验证数据
const validateData = () => {
  for (const item of tableData.items) {
    if (item.amount !== null && item.amount <= 0) {
      ElMessage.error(`金额必须大于0：${item.name}`)
      return false
    }
  }
  return true
}

// 获取处理后的数据
const getProcessedData = () => {
  return tableData.items
    .filter(item => item.amount !== null && item.amount > 0)
    .map(item => ({
      companyId: item.id,
      companyName: item.name,
      account: item.account,
      bankAddress: item.address,
      amount: item.amount,
      remark: item.remark.trim()
    }))
}
const useGroup = useGroupList()

// 下一步处理
const handleNextStep = () => {
  if (!validateData()) {
    return
  }

  const processedData = getProcessedData()
  
  if (processedData.length === 0) {
    ElMessage.warning('请至少输入一个有效的金额')
    return
  }
  console.log('处理后的数据：', processedData)
  
  // 这里可以发送到后端或进行其他处理
  ElMessage.success(`成功处理 ${processedData.length} 条数据`)
  
  useGroup.setGroupList(processedData)
  // router.push('')
  isSave.value = true
}

// 重置数据
const resetData = () => {
  initializeTableData()
  search.value = ''
  ElMessage.info('数据已重置')
}

onMounted(() => {
  initializeTableData()
})
// 一键设置备注
const initializeDataRemoark = () => {
  for(let i = 0;i<filteredList.value.length;i++){
    if(filteredList.value[i].name){
      filteredList.value[i].remark = filteredList.value[i].name.replace(
        /^(?:.*?市)?(.*?)(有限公司|科技有限公司|有限责任公司|股份有限公司|\（集团\）有限公司|集团有限公司|分公司|事务所|工作室|合作社)$/g,
        '$1'
      )+' ' + month + ' 月货款';
      tableData.items.filter(item => item.id === filteredList.value[i].id)[0].remark = filteredList.value[i].remark
    }
  }
  // console.log('filteredList',filteredList.value)
  ElNotification({
    title: '成功',
    message: '备注已一键设置',
    type: 'success',
    duration: 2000
  })
}
const router = useRouter()
const nextPage =()=>{
  const length = tableData.items.filter(item => item.amount !== null && item.amount > 0).length
  // console.log(!tableData.items.length!==filteredList.value.length)
  console.log('filteredList',filteredList.value.length)
  console.log('tableData',length)
  if(length===filteredList.value.length){
    router.push('/preview')
  }else{
    ElMessage.warning('请检查数据')
    return
  }
}

// 是否保存了
const isSave = ref(false)

</script>

<template>
  <div class="group-page">
    <div class="table-header">
      <el-input 
        v-model="search" 
        size="small" 
        placeholder="搜索公司/账号/开户行" 
        style="width: 300px; margin-right: 10px;"
      />
      <el-button type="success" @click="handleNextStep">保存</el-button>
      <el-button type="warning" @click="initializeDataRemoark">一键设置备注</el-button>
      <el-button type="danger" @click="resetData">重置</el-button>
      <el-button type="primary" v-if="isSave" @click="nextPage" >下一步</el-button>
    </div>

    <el-table 
      :data="filteredList" 
      style="width: 100%"
      empty-text="暂无数据"
    >
      <el-table-column label="ID" prop="id" width="40"  />
      <el-table-column label="收款单位" prop="name"  />
      <el-table-column label="账号" prop="account" />
      <el-table-column label="开户行" prop="address"  />
      
      <el-table-column label="金额" width="220">
        <template #default="{ row }">
          <el-input
            v-model="row.amount"
            placeholder="请输入金额"
            size="small"
            @input="(value) => handleAmountInput(value, row)"
            type="number"
            min="0"
            step="0.01"
          >
            <template #append>元</template>
          </el-input>
        </template>
      </el-table-column>
      
      <el-table-column label="备注" width="200">
        <template #default="{ row }">
          <el-input
            v-model="row.remark"
            placeholder="请输入备注"
            size="small"
            maxlength="50"
            show-word-limit
          />
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button 
            link 
            type="danger" 
            @click="row.amount = null; row.remark = ''"
            :disabled="!row.amount && !row.remark"
          >
            清空
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="summary" v-if="filteredList.length > 0">
      <p>已填写：{{ tableData.items.filter(item => item.amount !== null && item.amount > 0).length }} / {{ filteredList.length }} 条</p>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.group-page {
  padding: 20px;
}

.table-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
}

.summary {
  margin-top: 20px;
  text-align: center;
  color: #666;
  font-size: 14px;
}

:deep(.el-table .el-input__wrapper) {
  padding: 0 8px;
}

:deep(.el-table .el-input) {
  width: 100%;
}
</style>
